package com.right.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.right.entity.Admin;
import com.right.entity.Users;
import com.right.service.AdminService;
import com.right.service.impl.AdminServiceImp;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/AdminServlet")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       AdminService service=new AdminServiceImp();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String op = "";
		if (request.getParameter("op")!=null) {
			op = request.getParameter("op");
		}
		if ("login".equals(op)) {
			doLogin(request, response);
			System.out.println(op);
		}
		
	}
	/**
	 * 登录方法
	 * username用户名
	 * userpwd用户密码
	 * userService服务层方法
	 */
	public void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String adminname = request.getParameter("adminname");
		String adminpwd = request.getParameter("adminpwd");
		// 调用StoreDaoImpl对象的login方法登录验证
	
		if (service.login(adminname, adminpwd)) {
			request.getSession().setAttribute("adminname", adminname);
			//用户选择了记住密码
			if(request.getParameter("remember")!=null) {
				//创建cookie，并设置其过期时间，存储到本地
				Cookie cookie1 = new Cookie("adminname",adminname);
				cookie1.setMaxAge(60*60);//过期时间1h
				Cookie cookie2 = new Cookie("adminpwd",adminpwd);
				cookie2.setMaxAge(60*60);
				//将cookie的信息存储在本地: addCookie
				response.addCookie(cookie1);
				response.addCookie(cookie2);
			}
			//通过用户名查询用户id
			  int adminid =service.getIdByName(adminname).getAdminid();
			Admin admin = service.getAdminByid(adminid);

//			//将用户id记录在session中
			HttpSession session = request.getSession();
			session.setAttribute("admin", admin);
			request.getRequestDispatcher("adminuser.jsp").forward(request, response);
		}else {
			request.setAttribute("msg", "输入信息有误，请检查用户名或密码是否正确");
			request.getRequestDispatcher("adminlogin.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
